<?php

namespace app\api\model\v1;


use app\common\exception\Exception;
use think\Model;
use traits\model\SoftDelete;

class Activity extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'activity';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'starttime_text',
        'endtime_text'
    ];
    
    public function getMainimageAttr($value){
        return fiximgurl($value);
    }
    public function getDetailimageAttr($value){
        return fiximgurl($value);
    }
    public function getPosterimageAttr($value){
        return fiximgurl($value);
    }
    public function getStarttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['starttime']) ? $data['starttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    public function getEndtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['endtime']) ? $data['endtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    protected function setStarttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function store(){
        return $this->belongsTo(Store::class,"store_id")->removeOption("soft_delete");
    }
    public static function getList($params){
        extract($params);
        $where['statusswitch'] = 1;
        $where['starttime'] = ['elt',time()];
        if($type == 1){//进行中
            $where['endtime'] = ['gt',time()];
        }else if($type == 2){//已结束
            $where['endtime'] = ['elt',time()];
        }
        $list = self::with(['activity_sign'=>['user']])
        ->where($where)->field("id,name,price,trueprice,mainimage,starttime,endtime")
            ->paginate(10)->each(function($item,$index){
                if($item['endtime']>time()){//进行中
                    $item['status'] = "ing";
                }else if($item['endtime']<=time()){//已结束
                    $item['status'] = "finish";
                }
            });
        return $list->items();
    }
    public static function detail($activityId){
        $activity = self::with(['activity_sign'=>['user']])
            ->where(['id'=>$activityId,"statusswitch"=>1])
            ->field("id,name,address,longitude,latitude,intro,price,phone,
            trueprice,mainimage,detailimage,posterimage,starttime,endtime,readnums,
            posterswitch,phoneswitch,signmansswitch,signswitch,
            sharenums,signnums,poster_text_color,activity_form_ids")
            ->find();
        if(!$activity){
            new Exception("活动不存在");
        }
        if($activity['endtime']>time()){//进行中
            $activity['status'] = "ing";
        }else if($activity['endtime']<=time()){//已结束
            $activity['status'] = "finish";
        }
        //活动表单
        if($activity->activity_form_ids){
            $forms = ActivityForm::where(['id'=>['in',$activity->activity_form_ids]])
                ->field("id,title,isrequired,type,options")->select();
            if($forms){
                foreach ($forms as $k => $v){
                    $forms[$k]['options'] = $v['options']?explode(",",$v['options']):[];
                }
            }
            $activity['forms'] = $forms?:[];
        }
        return $activity;
    }

    public function activitySign(){
        return $this->hasMany(ActivitySign::class,"activity_id")
            ->field("id,user_id,activity_id,promoter_id,info")->limit(10);
    }

    public static function verifyActivity($activity){
        if(!$activity || $activity->statusswitch==0){
            new Exception("活动不存在或已下架");
        }
        if($activity->starttime>time() || $activity->endtime<time()){
            new Exception("活动未开始或已下架");
        }
        return true;
    }
    public static function issign($activityId,$userId){

        if(!$activityId){
            new Exception("活动不存在");
        }
        $activity = \app\api\model\v1\Activity::where(['id'=>$activityId,"statusswitch"=>1])->find();
        \app\api\model\v1\Activity::verifyActivity($activity);
        if($activity->manlimit!=0 && $activity->signnums>=$activity->manlimit){
            new Exception("活动名额已满，请查看其他活动");
        }
        $has = ActivitySign::where(['user_id'=>$userId,"activity_id"=>$activityId])->find();
        return $has?1:0;
    }

}
